/**
 * @Description: 流程管线
 * @Author: 李清
 * @Date: 2022-07-07 14:53:14
 */
export class Pipeline {
  /** 步骤索引 */
  public index = -1

  /** 步骤 */
  public steps: Function[] = null

  /** 所有步骤都完成的回调 */
  public progressCallback: PipelineProgressCallback = null

  /** 所有步骤都完成的回调 */
  public finishCallback: PipelineCallback = null

  /** 回调对象 */
  public target: any

  /** 管线参数 */
  public param: any

  /** 流转到下一个步骤 */
  public flow(err?: string) {
    if (err) {
      console.error(err)
      this.finishCallback && this.finishCallback(err, this.param)
      return
    }

    this.index++
    if (!this.steps || this.index >= this.steps.length) {
      this.finishCallback && this.finishCallback()
    } else {
      this.progressCallback && this.progressCallback(this.index, this.steps.length)
      const curStepFunc = this.steps[this.index]
      if (curStepFunc) {
        if (this.target) {
          curStepFunc.call(this.target, this.param)
        } else {
          curStepFunc(this.param)
        }
      } else {
        this.flow()
      }
    }
  }
}

export interface PipelineCallback {
  (err?: string, param?: any): void
}

export interface PipelineProgressCallback {
  (curStep: number, totalStep: number): void
}
